﻿using Api.Application.Command.RoleMenu;
using Domain;
using ErrorCode;
using Infrastructure;
using MediatR;
using System.Transactions;

namespace Api.Application.Handler.RoleMenu
{
    public class AddRoleMenuHandler : IRequestHandler<AddRoleMenuCommand, ApiResult<int>>
    {
        private readonly IBase<RoleModel> roleRepo;
        private readonly IBase<MenuModel> menuRepo;
        private readonly IBase<RoleMenuModel> roleMenuRepo;

        public AddRoleMenuHandler(IBase<RoleModel> roleRepo,IBase<MenuModel> menuRepo,IBase<RoleMenuModel> roleMenuRepo)
        {
            this.roleRepo = roleRepo;
            this.menuRepo = menuRepo;
            this.roleMenuRepo = roleMenuRepo;
        }
        public Task<ApiResult<int>> Handle(AddRoleMenuCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result=new ApiResult<int>();
            using (TransactionScope tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                var rolemenu = roleMenuRepo.GetAll().Where(x => x.RoleId == request.RoleId).ToList();
                 roleMenuRepo.Delete(rolemenu);
                List<RoleMenuModel> roleMenuModels = new List<RoleMenuModel>();
                foreach (var item in request.MenuId)
                {
                    roleMenuModels.Add(new RoleMenuModel()
                    {
                        MenuId = item,
                        RoleId = request.RoleId,
                    });
                }
                int count=roleMenuRepo.AddAsync(roleMenuModels).Result;
                if(count > 0)
                {
                    result.Code = ApiEnum.OK;
                    result.Msg = "分配成功";
                }
                else
                {
                    result.Code = ApiEnum.Fail;
                    result.Msg = "分配失败";
                }
                tran.Complete();
                return Task.FromResult(result);
            }
        }
    }
}
